/*
   Copyright (c) 2016-2017 Slamtec Co., Ltd. All Rights Reserved.
   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at
       http://www.apache.org/licenses/LICENSE-2.0
   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/

package com.csjbot.weedle_auto.Slam.agent


import java.util.*

internal class Worker {

    private val jobQueue = ArrayList<Runnable>()

    private val WorkerLock = Any()
    private var worker: Thread? = null
    private val runnable = Runnable {
        val jobs = ArrayList<Runnable>()

        while (true) {
            synchronized(jobQueue) {
                jobs.addAll(jobQueue)
                jobQueue.clear()
            }

            if (jobs.isEmpty()) {
                break
            }

            for (job in jobs) {
                // Logger.d("chenqi " + job);
                job.run()
            }
            jobs.clear()
        }

        synchronized(StateLock) {
            state = IDLE
        }
    }

    private var state: Int = 0
    private val StateLock = Any()

    init {
        state = IDLE
        worker = Thread(runnable)
    }

    fun push(job: Runnable) {
        synchronized(jobQueue) {
            jobQueue.add(job)
        }

        execute()
    }

    fun pushHead(job: Runnable) {
        synchronized(jobQueue) {
            jobQueue.add(0, job)
        }
        //        Csjlogger.debug("worker execute jobQueue = {}, size = {}", jobQueue.get(0).getClass(), jobQueue.size());
        execute()
    }

    fun clear() {
        synchronized(jobQueue) {
            jobQueue.clear()
        }
    }

    private fun execute() {
        //        Csjlogger.debug("worker execute state = {},worker.getState() = {}", state, worker.getState());
        synchronized(StateLock) {
            if (state == WORKING) {
                return
            }
            state = WORKING
        }

        if (worker!!.state == Thread.State.TERMINATED) {
            worker = Thread(runnable)
        }

        if (worker!!.state == Thread.State.WAITING) {
            synchronized(WorkerLock) {
                worker!!
            }
        }

        if (worker!!.state == Thread.State.NEW) {
            worker!!.start()
        }
    }

    companion object {
        private val TAG = "worker"

        private val IDLE = 0
        private val WORKING = 1
    }
}
